package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.*;
import cc.rengu.igas.bsps.common.dao.impl.*;
import cc.rengu.igas.bsps.common.entity.*;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.bean.MchntBindQrInfoBean;
import cc.rengu.igas.bsps.facade.request.MchntQrCodeBindListQueryRequest;
import cc.rengu.igas.bsps.facade.response.MchntQrCodeBindListQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020.03.28
 * 二维码绑定列表查询服务
 */
public class MchntQrCodeBindListQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntQrCodeBindListQueryRequest mchntQrCodeBindListQueryRequest = new MchntQrCodeBindListQueryRequest();
        ConvertUtil.convertOutput(mchntQrCodeBindListQueryRequest);
        return mchntQrCodeBindListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        MchntQrCodeBindListQueryRequest mchntQrCodeBindListQueryRequest = (MchntQrCodeBindListQueryRequest) request;
        MchntQrCodeBindListQueryResponse mchntQrCodeBindListQueryResponse = new MchntQrCodeBindListQueryResponse();
        List<MchntBindQrInfoBean> mchntBindQrInfoList = new ArrayList<>();
        /*获取法人行号信息*/
        String instId = mchntQrCodeBindListQueryRequest.getHeader().getInstId();
        /*获取用户信息*/
        String userId = mchntQrCodeBindListQueryRequest.getUserId();
        /*获取商户号信息*/
        String mchntNo = mchntQrCodeBindListQueryRequest.getMchntNo();
        /*获取角色信息*/
        String userRole = mchntQrCodeBindListQueryRequest.getUserRole();
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(userRole)) {
            rglog.error("必填性校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        List<QrCodeInfo> qrCodeInfoList = new ArrayList<>();
        BspsQrCodeInfoMapper qrCodeInfoMapper = new BspsQrCodeInfoMapperImpl();
        if ("00".equals(userRole)) {
            //商户查询
            BspsMchntBindInfoMapper bspsMchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
            MchntBindInfo mchntBindInfo = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, userId, mchntNo);
            if (null != mchntBindInfo) {
                /* 判断用户角色 */
                if ("00".equals(mchntBindInfo.getBindUserRole())) {
                    /* 用户为商户法人 */
                    qrCodeInfoList = qrCodeInfoMapper.selectBspsQrCodeInfo(instId, mchntNo);
                } else if ("01".equals(mchntBindInfo.getBindUserRole())) {
                    /* 用户为商户店长 */
                    qrCodeInfoList = qrCodeInfoMapper.selectBspsQrCodeInfoByMchntNo(instId, mchntNo);
                } else if ("02".equals(mchntBindInfo.getBindUserRole())) {
                    /* 用户为收银员 :调整发方法未跟进商户号收银员ID查询二维码列表 */
                    qrCodeInfoList = qrCodeInfoMapper.selectBspsQrCodeInfoByUserId(instId, userId);
                } else {
                    rglog.error("用户角色异常!");
                    throw new BizException(RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespDesc());
                }
            } else {
                rglog.error("查询用户角色信息失败!");
                throw new BizException(RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespDesc());
            }
        } else if ("10".equals(userRole)) {
            //拓展经理查询
            BspsManagerInfoMapper bspsManagerInfoMapper = new BspsManagerInfoMapperImpl();
            ManagerInfo managerInfo = null;
            if ("APP".equals(mchntQrCodeBindListQueryRequest.getHeader().getChanlId())){
                managerInfo = bspsManagerInfoMapper.selectBspsManagerInfoById(instId,userId);
            }else {
                managerInfo = bspsManagerInfoMapper.selectBspsManagerInfoByOpenId(instId, userId);
            }
            if (null == managerInfo || !"00".equals(managerInfo.getUserStatus())) {
                rglog.error("拓展经理信息异常!");
                throw new BizException(RespCodeEnum.GET_MANAGER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MANAGER_INFO_ERROR.getRespDesc());
            }
            //查询拓展经理是否可对商户操作
            BspsMchntBaseInfoMapper bspsMchntBaseInfoMapper = new BspsMchntBaseInfoMapperImpl();
            MchntBaseInfo mchntBaseInfo = bspsMchntBaseInfoMapper.selectBspsMchntBaseInfoByPrimaryKey(instId, mchntNo);
            if (null == mchntBaseInfo || "02".equals(mchntBaseInfo.getMchntStatus()) || "03".equals(mchntBaseInfo.getMchntStatus())) {
                rglog.error("商户信息异常!");
                throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
            }
            if (!managerInfo.getManagerId().equals(mchntBaseInfo.getManagerId())) {
                rglog.error("商户非该拓展经理商户!");
                throw new BizException(RespCodeEnum.USER_NO_AUTHORITY.getRespCode(), RespCodeEnum.USER_NO_AUTHORITY.getRespDesc());
            }
            qrCodeInfoList = qrCodeInfoMapper.selectBspsQrCodeInfo(instId, mchntNo);

        }

        if (!CollectionUtils.isEmpty(qrCodeInfoList)) {
            qrCodeInfoList.forEach(item -> covmchntBindQrInfo(item, mchntBindQrInfoList));
        }
        /* 重组返回结果 */
        BizResponse<MchntQrCodeBindListQueryResponse> bizResponse = new BizResponse<>();
        mchntQrCodeBindListQueryResponse.setMchntBindQrInfoList(mchntBindQrInfoList);
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntQrCodeBindListQueryResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntQrCodeBindListQueryResponse mchntQrCodeBindListQueryResponse = (MchntQrCodeBindListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntQrCodeBindListQueryResponse);
    }

    /**
     * 转换二维码列表信息
     *
     * @param qrCodeInfo 二维码信息
     *                   mchntBindQrInfoList 应答接口信息
     */

    private void covmchntBindQrInfo(QrCodeInfo qrCodeInfo, List<MchntBindQrInfoBean> mchntBindQrInfoList) {
        try {
            MchntBindQrInfoBean mchntBindQrInfo = new MchntBindQrInfoBean();
            BeanUtil.beanCopy(qrCodeInfo, mchntBindQrInfo);
            //二维码logo图标赋值
            if (!StringUtil.isEmptyOrNull(qrCodeInfo.getLogoUrlPath())) {
                mchntBindQrInfo.setLogoImagePath(Base64.encodeBase64String(qrCodeInfo.getLogoUrlPath().getBytes()));
            }
            /*   获取用户昵称信息    */
            UserInfoMapper userInfoMapper = new UserInfoMapperImpl();
            UserInfo userInfo = userInfoMapper.selectBspUserInfoByPrimaryKey(qrCodeInfo.getInstId(), qrCodeInfo.getUserId());
            if (null != userInfo) {
                mchntBindQrInfo.setUserName(userInfo.getNickName());
            }
            /*  获取商户名称信息             */
            BspsMchntBaseInfoMapper mchntBaseInfoMapper = new BspsMchntBaseInfoMapperImpl();
            MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectBspsMchntBaseInfoByPrimaryKey(qrCodeInfo.getInstId(), qrCodeInfo.getMchntNo());
            if (null != mchntBaseInfo) {
                mchntBindQrInfo.setMchntName(mchntBaseInfo.getMchntName());
                mchntBindQrInfo.setMchntType(mchntBaseInfo.getMchntType());
            }
            mchntBindQrInfo.setQrName(qrCodeInfo.getQrCodeName());
            mchntBindQrInfoList.add(mchntBindQrInfo);
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("二维码列表查询详息转换失败:{}", byteArrayOutputStream.toString());
        }

    }
}
